﻿import util from '@/libs/util.js'
// import Vue from 'vue'
// import vueSocketio from 'vue-socket.io'
// import socketio from 'socket.io-client'
import loginApi from '@/api/login'
import { SystemPrompt } from '@/enums/SystemPrompt'
import { validatenull } from '@/libs/validate'

export default {
  namespaced: true,
  actions: {
    /**
     * @author jing.fu@topevery.club
     * @date 2018/11/26 11:26:08
     * @Description: 登录
     */
    loginByUsername({ commit, state, dispatch }, { vm, userInfo, route = { name: 'index' } }) {
      return new Promise((resolve, reject) => {
        const user = util.encryption({
          data: userInfo,
          key: '1234567887654321',
          param: ['password']
        })

        loginApi.login(user.username, user.password, user.verifyCode, user.randomStr, 'password')
          .then(async response => {
            const data = response.data
            await dispatch('setToken', {
                vm: vm,
                accessToken: data.access_token,
                refreshToken: data.refresh_token,
                expiresIn: data.expires_in
            })
          })
          .catch(err => {
            reject(err)
          })
      })
    },

    setToken({ commit, state, dispatch }, { vm, accessToken, refreshToken, expiresIn, route = { name: 'index' } }) {
        commit('topevery/token/SET_ACCESS_TOKEN', accessToken, { root: true })
        commit('topevery/token/SET_REFRESH_TOKEN', refreshToken, { root: true })
        commit('topevery/token/SET_EXPIRES_IN', expiresIn, { root: true })
        // util.cookies.set('uuid', data.access_token)
        util.cookies.set('token', accessToken)
        const path = util.cookies.get('redirect')
        vm.$router.replace(path ? { path } : route)
        util.cookies.remove('redirect')
        // 用户登陆后从数据库加载一些基础数据
        dispatch('bindCurrentUser', {
            vm: vm
        })
    },

    bindCurrentUser({ commit, state, dispatch }, { vm }) {
      return new Promise((resolve, reject) => {
        loginApi.bindCurrentUser()
          .then(async res => {
            if (!validatenull(res)) {
              dispatch('getUserInfo', {
                vm: vm
              })
            }
          })
          .catch(err => {
            reject(err)
          })
      })
    },

    getUserInfo({ commit, state, dispatch }, { vm }) {
      loginApi.getUserInfo()
        .then(async res => {
          console.log('res', res)
          const userInfo = res.data
          const roles = userInfo.roles
          roles.forEach((role) => {
            switch (role.category) {
              case '0':
                role.icon = 'ty icon-user'
                role.color = '#4297fa'
                break
              case '3':
                role.icon = 'ty icon-paiqian1'
                role.color = '#b3d462'
                break
              case '1':
                role.icon = 'ty icon-shouliyuan'
                role.color = '#f8b752'
                break
              case '4':
                role.icon = 'ty icon-zhibanchang1'
                role.color = '#5f539e'
                break
              case '2':
                role.icon = 'ty icon-jianduyuanpingjia'
                role.color = '#497cc0'
                break
              case '5':
                role.icon = 'ty icon-jigou'
                role.color = '#2fa1d8'
                break
              case '6':
                role.icon = 'ty icon-shift-foreman'
                role.color = '#82cd5f'
                break
              default:
                role.icon = 'ty icon-role-personnel'
                role.color = '#4094ff'
                break
            }
          })
          commit('topevery/token/SET_OPEN_KEEP_ONLINE', userInfo.customAppInfo.openKeepOnline, { root: true })
          commit('d2admin/user/SET_ROLES', roles, { root: true })
          commit('d2admin/user/SET_USER_INFO', userInfo, { root: true })
          commit('d2admin/user/SET_PERMISSIONS', userInfo.permissions || [], { root: true })
          if (roles.length > 0) {
           await dispatch('updateCurrentUser', { vm, userInfo: userInfo, role: roles[0] })
          }
          /**
           * @author jing.fu@topevery.club
           * @date 2018/12/20 10:40:08
           * @Description: 登录成功后加载一些基础字典
           */
          await dispatch('topevery/dictionary/SetCommonDics', {}, { root: true })
          await dispatch('topevery/mapLayerIcon/SetMapLayerIcon', {}, { root: true })

          /**
           * @Author yuesheng.zhu@topevery.club
           * @Date 2019/5/7 16:53
           * @Description 登录成功后加载地图服务配置
           */
          await dispatch('topevery/map/SetMapServerInfo', {}, { root: true })
          await dispatch('d2admin/user/set', { name: userInfo.username }, { root: true })
          await dispatch('load')
        })
        .catch(() => {
          console.group('GETUSERINFO FAIL')
        })
    },

    /**
     * @author jing.fu@topevery.club
     * @date 2019/04/25 17:13:52
     * @Description: 更新用户角色信息
     */
    updateCurrentUser({ commit, state, dispatch, rootState }, { vm, userInfo, role }) {
      commit('d2admin/user/SET_CURRENT_ROLE', role, { root: true })
      userInfo.defaultRole = role
      loginApi.updateCurrentUser(userInfo)
        .then((ret) => {
          dispatch('d2admin/menu/getMenuTreeByRoleIds', vm, { root: true })
        })
        .catch(() => {
          vm.$confirm(`${SystemPrompt.Login.updateCurrentUser}`, `${SystemPrompt.SystemTips}`,
            {
              confirmButtonText: `${SystemPrompt.Login.button.confirm}`,
              cancelButtonText: `${SystemPrompt.Login.button.cancel}`,
              type: 'warning'
            })
            .then(() => {
              dispatch('updateRoleInfo', { vm, role })
            })
            .catch(() => {
              dispatch('exitProgram', { vm: vm })
            })
        })
    },
    /**
     * @description 注销用户并返回登陆页面
     * @param {Object} param context
     * @param {Object} param vm {Object} vue 实例
     * @param {Object} param confirm {Boolean} 是否需要确认
     */
    loginOut({ commit, state, dispatch }, { vm, confirm = false }) {
      /**
       * @description 注销
       */
      function exit() {
        loginApi.loginOut()
          .then((res) => {
            dispatch('exitProgram', { vm: vm })
          })
          .catch(() => {
            vm.$message.error(`${SystemPrompt.LoginOut.failMsg}`)
          })
      }

      // 判断是否需要确认
      if (confirm) {
        commit('d2admin/gray/set', true, { root: true })

        vm.$confirm(`${SystemPrompt.LoginOut.content}`, `${SystemPrompt.LoginOut.title}`, {
          confirmButtonText: `${SystemPrompt.LoginOut.button.confirm}`,
          cancelButtonText: `${SystemPrompt.LoginOut.button.cancel}`,
          type: 'warning'
        })
          .then(() => {
            commit('d2admin/gray/set', false, { root: true })

            exit()
          })
          .catch(() => {
            commit('d2admin/gray/set', false, { root: true })
          })
      } else {
        exit()
      }
    },
    exitProgram({ commit, dispatch }, { vm }) {
      // 删除cookie
      util.cookies.remove('token')
      util.cookies.remove('uuid')
      // 跳转路由
      // 清除菜单
      // commit('d2admin/user/SET_MENU', [], { root: true })
      // 清除权限
      // commit('d2admin/user/SET_PERMISSIONS', [], { root: true })
      // 清除用户信息
      // commit('d2admin/user/SET_USER_INFO', {}, { root: true })
      commit('modules/token/SET_ACCESS_TOKEN', '', { root: true })
      commit('modules/token/SET_REFRESH_TOKEN', '', { root: true })
      commit('modules/token/SET_EXPIRES_IN', '', { root: true })
      // commit('d2admin/user/SET_ROLES', [], { root: true })
      // commit('d2admin/user/SET_CURRENT_ROLE', {}, { root: true })
      // commit('d2admin/log/clear', {}, { root: true })
      // commit('d2admin/search/init', [], { root: true })
      // dispatch('d2admin/page/closeAll', vm, { root: true })
      // dispatch('d2admin/user/set', { name: '' }, { root: true })
      // commit('DEL_ALL_TAG')
      // removeToken()
      // removeUserName()
      // delete layui.layim

      // util.cookies.set('redirect', vm.$route.fullPath)

      vm.$router.push({
        path: '/login'
      })
    }
    /**
     * @description 用户登录后从持久化数据加载一系列的设置
     * @param {Object} context
     */
    // load({ dispatch }) {
    //   return new Promise(async resolve => {
    //     // DB -> store 加载用户名
    //     await dispatch('d2admin/user/load', null, { root: true })
    //     // DB -> store 加载主题
    //     await dispatch('d2admin/theme/load', null, { root: true })
    //     // DB -> store 加载页面过渡效果设置
    //     await dispatch('d2admin/transition/load', null, { root: true })
    //     // DB -> store 持久化数据加载上次退出时的多页列表
    //     await dispatch('d2admin/page/openedLoad', null, { root: true })
    //     // DB -> store 持久化数据加载侧边栏折叠状态
    //     await dispatch('d2admin/menu/asideCollapseLoad', null, { root: true })
    //     // DB -> store 持久化数据加载全局尺寸
    //     await dispatch('d2admin/size/load', null, { root: true })
    //     // DB -> store socket创建连接
    //     // await dispatch('d2admin/user/connect', null, { root: true })
    //     // end
    //     resolve()
    //   })
    // }
  }
}
